//
//  This file is part of iPhoneSMS.
//
//  iPhoneSMS is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  iPhoneSMS is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with iPhoneSMS.  If not, see <http://www.gnu.org/licenses/>.
//
//  Conversation.m
//  iPhoneSMS
//
//  Created by Billy Cahill on 2/8/10.
//  Copyright 2010 Billy Cahill.
//

#import "Conversation.h"

@implementation Conversation

-init {
	self = [super init];
	phoneno = -1;
	msgs = nil;
	return self;
}

-(void)dealloc {
	phoneno = 0;
	[msgs release];
	
	[super dealloc];
}

-(void)setPhoneNo:(int)n {
	phoneno = n;
}

-(void)setMessages:(Messages*)m {
	[msgs release];
	
	msgs = [m retain];
}

-(int)count {
	NSArray* ary = [msgs array];
	NSEnumerator *emu = [ary objectEnumerator];
	NSDictionary* dic;
	int rv = 0;
	while( dic = [emu nextObject] ) {
		NSString* no = [dic objectForKey:@"no"];
		if ( [no intValue] == phoneno ) {
			rv++;
		}
	}
	
	return rv;
}

-(NSDictionary*)objectAtIndex:(int)idx {
	NSArray* ary = [msgs array];
	NSEnumerator *emu = [ary objectEnumerator];
	NSDictionary* dic;
	int rv = 0;
	while( dic = [emu nextObject] ) {
		NSString* no = [dic objectForKey:@"no"];
		if ( [no intValue] == phoneno ) {
			if ( rv == idx ) {
				return dic;
			}
			rv++;
		}
	}
	
	return nil;
}

- (id)tableView:(NSTableView *)aTableView
objectValueForTableColumn:(NSTableColumn *)aTableColumn
			row:(int)rowIndex  {
    id theRecord, theValue;
	
    NSParameterAssert(rowIndex >= 0 && rowIndex < [self count]);
	
    theRecord = [self objectAtIndex:rowIndex];
	
    theValue = [theRecord objectForKey:[aTableColumn identifier]];
	
    return theValue;
}

- (int)numberOfRowsInTableView:(NSTableView *)aTableView {
    return [self count];
}

- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex {
	
	NSTextFieldCell *cell = aCell;
	
	NSTextFieldCell* temp;
	
	if ( 0 == (rowIndex%2) ) {
		temp = even;
	} else {
		temp = odd;
	}
	
	[cell setBackgroundColor:[temp backgroundColor]];
}

@end
